package com.somsoft.handjc.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.somsoft.handjc.util.BaseActivity;
import com.somsoft.handjc.util.MD5;
import com.somsoft.handjc.util.MyApplication;
import com.somsoft.handjc.util.Utils;

public class LoginActivity extends BaseActivity {
	private Button btnLogin = null;
	private CheckBox chkBox = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.login);
		btnLogin = (Button)findViewById(R.id.signin_button);
		btnLogin.setOnClickListener(new OnClickListenerImpl());
		
		chkBox = (CheckBox)findViewById(R.id.checkBox1);
		
		//如果ip文件不存在，则创建
		try {
			File file = new File("/data/data/com.somsoft.handjc.activity/files/ip.txt");
			File fileRember = new File("/data/data/com.somsoft.handjc.activity/files/rember.txt");
			File filePwd = new File("/data/data/com.somsoft.handjc.activity/files/password.txt");
			if(!file.exists()){
				writeFileData("ip.txt","http://192.168.1.100:8088");
			}else{
				Utils.SERVER_IP = readFileData("ip.txt");
			}
			if(fileRember.exists()){
				Utils.REMBER_ME = readFileData("rember.txt");
			}
			if(filePwd.exists()){
				String[] tp = readFileData("password.txt").split("★");
				if(tp.length==2){
					Utils.USERNAME = tp[0];
					Utils.PASSWORD = tp[1];
				}else{
					Utils.USERNAME = "";
					Utils.PASSWORD = "";
				}
			}
			
			
			if("true".equals(Utils.REMBER_ME)){
				chkBox.setChecked(true);
				EditText username = (EditText)findViewById(R.id.username_edit);
				EditText password = (EditText)findViewById(R.id.password_edit);
				username.setText(Utils.USERNAME);
				password.setText(Utils.PASSWORD);
			}else{
				chkBox.setChecked(false);
			}
		} catch (Exception e) {
			Toast.makeText(LoginActivity.this, "读取配置文件失败！", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class OnClickListenerImpl implements OnClickListener{

		@Override
		public void onClick(View v) {
			
			//Utils.openLoading(LoginActivity.this);
			
			EditText username = (EditText)findViewById(R.id.username_edit);
			EditText password = (EditText)findViewById(R.id.password_edit);
			//登录验证
			List <NameValuePair> params=new ArrayList<NameValuePair>();   
			params.add(new BasicNameValuePair("username",username.getText().toString()));   
			params.add(new BasicNameValuePair("password",new MD5().getMD5ofStr(password.getText().toString())));   
			
			try {
				String result = Utils.getJsonData(Utils.SERVER_IP + "/handweb/system/system!login.hand", params);
				if(result != null && !result.equals("null")){
					
					//保存是否记住密码
					if(chkBox.isChecked()){
						writeFileData("rember.txt","true");
						writeFileData("password.txt",username.getText().toString() +"★"+ password.getText().toString());
					}else{
						writeFileData("rember.txt","false");
						writeFileData("password.txt","");
					}
					JSONObject obj = new JSONObject(result);
					Utils.closeLoading();
					Utils.LOGIN_USER = username.getText().toString();
					Utils.USER_LEVEL = obj.getInt("level");
					Intent it = new Intent(LoginActivity.this,MainActivity.class);
					startActivity(it);
//					finish();
				}else{
					Toast.makeText(LoginActivity.this, "登录失败！用户名或密码错误！", Toast.LENGTH_SHORT).show();
				}
//				Intent it = new Intent(LoginActivity.this,MainActivity.class);
//				startActivity(it);
//				finish();
			} catch (Exception e) {
				Toast.makeText(LoginActivity.this, "连接服务器超时！", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		super.onCreateOptionsMenu(menu);
		menu.removeItem(10);
		menu.add(Menu.NONE, 50, 50, "设置IP").setIcon(android.R.drawable.ic_menu_set_as);
		return true;											
	}
	
	public void writeFileData(String fileName, String message) throws Exception{
		try {
			FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
			byte[] bytes = message.getBytes();
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			throw e;
		}
	}
	
	public String readFileData(String fileName) throws Exception{
		String res = "";
		try {
			FileInputStream fin = openFileInput(fileName);
			int length = fin.available();
			byte[] buffer = new byte[length];
			fin.read(buffer);
			res = EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
		}catch (Exception e) {
			throw e;
		}
		return res;
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
			Dialog dialog = new AlertDialog.Builder(this)
			.setTitle("提示")
			.setMessage("确认退出吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					MyApplication.getInstance().exit();
				}
			})
			.setNegativeButton("取消",new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
				
			}).create();
			dialog.show() ;
			return true;
		}else{
			return false;
		}
	}
}